package com.maori.languageapp.discover;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maori.languageapp.R;
import com.maori.languageapp.consts.JSONfunctions;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;

public class Maori_Discover_Phrase extends Activity {
	// Declare Variables
	JSONObject jsonobject,jsonobjectres;
	JSONArray jsonarray;
	ListView listview;
	Maori_Discover_Phrase_Adapter adapter;
	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	static String MID = "MID";
	static String NID = "NID";
	static String Phrase = "Phrase";
	static String Phraseb = "Phraseb";
	static String M_Source = "M_Source";
	static String first_name = "first_name";
	static String last_name = "last_name";
	static String tribe = "tribe";
	static String userimage = "userimage";
	static String TotalsLikes = "TotalsLikes";
	static String TotalsSynonim = "TotalsSynonim";
	static String TotalImages = "TotalImages";
	static String TotalAudios = "TotalAudios";
	static String TotalVideos = "TotalVideos";
	
	static String NCMIDStr = "NCMIDStr";
	
	int NCMID;
	String node_category;
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	JSONArray jArray;
	HttpParams httpParameters = new BasicHttpParams();
	TextView txtHeading;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.maori_discover_list_panel);
		
		txtHeading  =  (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Discover Phrase");
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			NCMIDStr  = extras.getString("NCMID"); 
			 node_category = extras.getString("node_category");
			 //NCMIDStr = Integer.toString(NCMID); 
		}
		// Execute DownloadJSON AsyncTask
		new DownloadJSON().execute();

	}

	// DownloadJSON AsyncTask
	private class DownloadJSON extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;


		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_Discover_Phrase.this);
			// Set progressdialog title
			mProgressDialog.setTitle("Download Phrase Details:"+NCMIDStr + "=" + node_category);
			// Set progressdialog message
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost("http://langapp.testarea.co.nz/maoriapi/getFilteredDiscoverPhrase.php");
				JSONObject json = new JSONObject();
				json.put("record1", NCMIDStr);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Login Result *****:" + result);
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								HashMap<String, String> map = new HashMap<String, String>();
								map.put("Phrase", c.getString("Phrase"));
								map.put("Phraseb", c.getString("Phraseb"));
								map.put("NID", c.getString("NID"));
								map.put("M_Source", c.getString("M_Source"));
								map.put("MID", c.getString(MID));
								map.put("first_name", c.getString("first_name"));
								map.put("last_name", c.getString("last_name"));
								map.put("tribe", c.getString("tribe"));
								map.put("userimage", c.getString("userimage"));
								map.put("TotalsLikes", c.getString("TotalsLikes"));
								map.put("TotalsSynonim", c.getString("TotalsSynonim"));
								map.put("TotalImages", c.getString("TotalImages"));
								map.put("TotalAudios", c.getString("TotalAudios"));
								map.put("TotalVideos", c.getString("TotalVideos"));
								// Set the JSON Objects into the array
								arraylist.add(map);
							}
						}
						catch (Exception e) {
							Log.v(TAG, "***** Exception *****:" + e);
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		
		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			listview = (ListView) findViewById(R.id.listviewdiscover);
			// Pass the results into ListViewAdapter.java
			adapter = new Maori_Discover_Phrase_Adapter(Maori_Discover_Phrase.this,
					arraylist);
			// Binds the Adapter to the ListView
			listview.setAdapter(adapter);
			// Close the progressdialog
			mProgressDialog.dismiss();
		}
	}
}
